<?php

class News_Application_Thread
{
    var $Controller; 
    var $Db; 
	function News_Application_Thread($controller)
    {
        $this->Controller = $controller;
		$this->Db = new News_Application_MySQLConnection($this->Controller);
    }
	
	function Clear ()
	{
		$sql    = "DELETE FROM ThreadData;";
	    $this->Db->Execute ($sql);
    }
	
	function Read ()
	{
		$sql    = "SELECT * FROM ThreadData;";
		$result = $this->Db->Execute ($sql);
		$ret    = array();
		if (mysql_num_rows($result) > 0)  
		{
		    while ($row = mysql_fetch_assoc($result)) 
		    {
			    $ret[] = $row;
			}
		} 
		$this->Db->Close (); 
		return $ret;
	}
	
	function Add ($message, $value, $max, $group = '', $index = NULL)
	{
		$message = str_replace ("'", "\\'", $message); 
		for ($x=$index-1;$x>-1;$x--) 
		{
			$sql = "SELECT * FROM ThreadData WHERE ThreadIndex = {$x};";
			$result = $this->Db->Execute ($sql);
			if (mysql_num_rows($result) == 0)  
			{
			    $sql = "INSERT INTO ThreadData (ThreadIndex, ThreadMessage, ThreadGroup) " . 
				       "                       VALUES ({$x}, 'Waiting...', '{$group}');";
		        echo $sql . "\n----------------\n";
				$ret = $this->Db->Execute ($sql);
				var_dump($ret);
			} 
		}
		
		$sql = "SELECT * FROM ThreadData WHERE ThreadIndex = {$index};";
		$result = $this->Db->Execute ($sql);
		if (mysql_num_rows($result) == 0)  
		{
		    $sql = "INSERT INTO ThreadData (ThreadIndex, ThreadValue, ThreadMax, ThreadMessage, ThreadGroup) " . 
			       "                       VALUES ({$index}, {$value}, {$max}, '{$message}', '{$group}');";
		} 
		else { 
		    $sql = "UPDATE ThreadData SET ThreadValue={$value}," . 
		           "                      ThreadMax={$max}," . 
		           "                      ThreadMessage='{$message}'," . 
		           "                      ThreadGroup='{$group}' WHERE ThreadIndex={$index};";
		}
		echo $sql . "\n----------------\n";
	    $this->Db->Execute ($sql); 
		$this->Db->Close (); 
	}
} 
?>